<template>
  <div v-if="$route.path === '/things-lists/addThings'" class="add-things">
    <!-- 步骤条 -->
    <el-steps :active="active" finish-status="success">
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品信息"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
    </el-steps>
    <!-- 标签页 -->
    <el-tabs class="add-main" tab-position="left">
      <el-tab-pane label="基本信息">
        <el-form
          :model="newThing"
          :rules="rules"
          ref="addThing"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="newThing.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input type="number" v-model="newThing.goods_price"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input type="number" v-model="newThing.goods_weight"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input type="number" v-model="newThing.goods_number"></el-input>
          </el-form-item>
          <el-form-item
            v-if="!editThings.isEditThing"
            label="商品分类"
            prop="goods_cat"
          >
            <el-cascader
              class="cascader"
              clearable
              v-model="newThing.goods_cat"
              :props="props"
              :options="allParamaterList"
            >
            </el-cascader>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="商品参数">商品参数</el-tab-pane>
      <el-tab-pane label="商品信息">商品信息</el-tab-pane>
      <el-tab-pane label="商品图片">
        <el-upload
          class="upload-demo"
          :headers="{ Authorization: token }"
          action="http://127.0.0.1:8888/api/private/v1/upload/"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleUp"
          :file-list="fileListMain"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-tab-pane>
      <el-tab-pane label="商品内容">
        <editor
          id="goods_introduce"
          api-key="9mieih2cqsubf30b1omff3w107ojvjfvzhmb7haq4giiy754"
          :init="{
            height: 500, //菜单
            menubar: false, //插件
            plugins: [
              'advlist autolink lists link image charmap print preview anchor',
              'searchreplace visualblocks code fullscreen',
              'insertdatetime media table paste code help wordcount',
            ], //工具栏配置
            toolbar:
              'undo redo | formatselect | bold italic backcolor | \ alignleft aligncenter alignright alignjustify | \ bullist numlist outdent indent | removeformat | help',
          }"
        />
        <el-button class="margin-top15" @click="upThings" type="primary"
          >添加商品</el-button
        >
      </el-tab-pane>
    </el-tabs>
    <!-- <button @click="test()">test</button> -->
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="35%">
      <img class="lookImg" :src="imgUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import Editor from "@tinymce/tinymce-vue";
import { mapMutations, mapState } from "vuex";
export default {
  components: {
    editor: Editor,
  },
  data() {
    return {
      oldImg: [],
      active: 0,
      newThing: {
        goods_name: "",
        goods_cat: [], //分类列表
        goods_price: null,
        goods_number: null,
        goods_weight: null,
        goods_introduce: "", //介绍
        pics: [],
        attrs: null, //参数
      },
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      //商品分类列表
      allParamaterList: null,
      //列表包含子级的项
      props: {
        label: "cat_name",
        value: "cat_id",
        expandTrigger: "hover",
      },
      //图片上传
      fileListMain: [],
      fileListBox: [],
      token: "",

      //图片预览图片地址
      imgUrl: "",
      dialogVisible: false,
    };
  },
  computed: {
    ...mapState(["editThings"]),
  },

  watch: {
    newThing: {
      handler(newValue) {
        if (this.newThing.goods_price < 0) {
          this.newThing.goods_price = 0;
        }
        if (this.newThing.goods_number < 0) {
          this.newThing.goods_number = 0;
        }
        if (this.newThing.goods_weight < 0) {
          this.newThing.goods_weight = 0;
        }
      },
      deep: true,
    },
    //判断是否是编辑商品
  },
  methods: {
    //获取下拉列表内的树形结构
    async getAllParamater() {
      const res = await this.$axios.get("categories");
      this.allParamaterList = res.data.data;
    },
    //上传以及移除图片
    handleRemove(fileList) {
      // console.log(fileList);
      this.fileListBox = fileList;
    },
    handlePreview(file) {
      // console.log(file);
      this.imgUrl = file.url;
      this.dialogVisible = true;
    },
    handleUp(file) {
      this.fileListBox.push(file.data);
      // console.log(this.fileListBox);
    },

    //获取内容
    getContent() {},
    ...mapMutations(["changeIs"]),
    //上传商品
    async upThings() {
      this.newThing.goods_introduce =
        tinyMCE.editors["goods_introduce"].getContent();
      this.newThing.pics = [
        // ...this.oldImg,
        ...this.fileListBox.map((ele) => {
          return { pic: ele.tmp_path };
        }),
      ];
      const {
        goods_name,
        goods_cat,
        goods_price,
        goods_number,
        goods_weight,
        goods_introduce,
        pics,
        attrs,
      } = this.newThing;

      if (Array.isArray(this.newThing.goods_cat)) {
        this.newThing.goods_cat = goods_cat.join(",");
      }
      if (goods_name === "") {
        this.$message.error("商品名称不能为空");
      } else if (goods_cat === []) {
        this.$message.error("商品分类不能为空");
      } else if (!goods_price) {
        this.$message.error("商品价格不能为空");
      } else if (!goods_number) {
        this.$message.error("商品数量不能为空");
      } else if (!goods_weight) {
        this.$message.error("商品重量不能为空");
      } else {
        if (!this.editThings.isEditThing) {
          const res = await this.$axios.post("goods", this.newThing);
          if (res.data.meta.status === 201) {
            this.$message({
              message: "添加商品成功",
              type: "success",
            });
            console.log(res);
            this.$router.push("/things-lists");
          } else {
            this.$message({
              message: `${res.data.meta.msg}`,
              type: "warning",
            });
            console.log(res);
          }
        } else {
          const res = await this.$axios.put(
            `goods/${this.editThings.isEditThing}`,
            {
              goods_cat,
              goods_name,
              goods_price,
              goods_number,
              goods_weight,
              goods_introduce,
              pics,
              attrs,
            }
          );
          if (res.data.meta.status === 200) {
            this.$message({
              message: "编辑商品成功",
              type: "success",
            });
            // console.log(res);
            this.changeIs(false);
            (this.newThing = {
              goods_name: "",
              goods_cat: [], //分类列表
              goods_price: null,
              goods_number: null,
              goods_weight: null,
              goods_introduce: "", //介绍
              pics: [],
              attrs: null, //参数
            }),
              this.$router.push("/things-lists");
          } else {
            this.$message({
              message: `${res.data.meta.msg}`,
              type: "warning",
            });
            console.log(res);
          }
        }
      }
    },

    // test() {
    //   console.log([
    //     ...this.oldImg,
    //     ...this.fileListBox.map((ele) => {
    //       return { pic: ele.tmp_path };
    //     }),
    //   ]);
    // },
  },
  async created() {
    this.getAllParamater();
    this.token = window.sessionStorage.getItem("token");
    if (this.editThings.isEditThing) {
      const res = await this.$axios.get(`goods/${this.editThings.isEditThing}`);
      console.log(res);
      this.newThing = res.data.data;
      this.fileListMain = res.data.data.pics.map((ele) => {
        return { url: ele.pics_big_url, name: ele.pics_id };
      });
      if (res.data.data.goods_introduce) {
        tinyMCE.editors["goods_introduce"].setContent(
          res.data.data.goods_introduce
        );
      }
    }
    this.oldImg = [
      ...this.newThing.pics.map((ele) => {
        return { pic: ele.pics_big };
      }),
    ];
  },
};
</script>

<style lang='less'>
.add-things {
  .add-main {
    margin-top: 15px;
  }
}
.el-scrollbar__wrap {
  height: 250px !important;
}
.cascader {
  width: 30% !important;
}
.lookImg {
  width: 100%;
  height: auto;
}
</style>